import pathlib

from kivy.properties import StringProperty, OptionProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.dropdown import DropDown

from common import KvLoad, SoundSham
from common.date_tools import sec_to_hms
from ui.audio_player.base_weight import PlayBase

options_dict = {'primary': '主音轨道', 'secondary': '新音轨道'}  # 暂不支持 'backdrop': '背景音乐'


class PlayRow(BoxLayout, PlayBase):
    text_current_music_play_time = StringProperty('00:00:00')
    track_type = OptionProperty('primary', options=list(options_dict.keys()))  # 当前音轨类型

    def __init__(self, **kwargs):
        """
            主要的音轨播放行
        :param kwargs:
        """
        KvLoad.load(__file__)
        super().__init__(**kwargs)
        self.ids.id_play_slider.bind(on_touch_down=self.on_slider_touch_down)
        self.ids.id_play_slider.bind(on_touch_up=self.on_slider_touch_up)
        self.ids.id_sound_volume_slider.bind(value=self.update_sound_volume)
        self.ids.id_button_dropdown.text = options_dict.get(self.track_type)
        self.ids.id_button_dropdown.bind(on_release=self.init_dropdown)
        self.on_clear_audio_update_ui()

    def init_dropdown(self, widget):
        dropdown = DropDown(on_select=self.on_select_track_type)
        for option in options_dict.keys():
            # 增加选择音频输出按钮
            btn_text = options_dict.get(option)
            dropdown.add_widget(Button(text=btn_text, size_hint_y=None, height=widget.height,
                                       font_size=widget.font_size,
                                       on_release=lambda bt: dropdown.select(bt.text)))

        dropdown.open(widget)

    def on_select_track_type(self, widget, value):
        _ = widget
        self.ids.id_button_dropdown.text = value
        for track_type in options_dict:
            if options_dict.get(track_type) == value:
                self.track_type = track_type
                self.update_track_type()

    def update_track_type(self):
        """更新音轨类型时触发"""
        if self.track_type in ('primary', 'secondary'):
            self.group = 'grid'  # 与互动音轨为一个组
        else:
            self.group = None

    def on_updater_ui(self):
        if not self.auto_move_slider:
            self.ids.id_play_slider.set_value(self.seek_value)
        self.text_current_music_play_time = sec_to_hms(self.sound.get_pos())

    def on_pause_or_proceed_update_ui(self):
        if self.play_state == 'pause':
            self.ids.id_pause_or_proceed_button.source = self.play_icon
        else:
            self.ids.id_pause_or_proceed_button.source = self.pause_icon

    def on_sound_load(self):
        if self.sound is None:
            return
        self.ids.id_file_name_text.text = pathlib.Path(self.sound.source).stem
        self.ids.id_music_length_text.text = f'00:00:00 - {sec_to_hms(self.sound.length)}'
        self.ids.id_play_slider.max = int(self.sound.length)
        self.ids.id_state_icon.source = self.y_icon

    def on_clear_audio_update_ui(self):
        self.ids.id_play_slider.set_value(self.seek_value)
        self.ids.id_file_name_text.text = ''
        self.ids.id_music_length_text.text = '00:00:00 - 00:00:00'
        self.text_current_music_play_time = '00:00:00'
        self.ids.id_pause_or_proceed_button.source = self.play_icon
        self.ids.id_state_icon.source = self.x_icon
        self.update_track_type()

    def on_play_completed_update_ui(self):
        self.ids.id_play_slider.set_value(self.seek_value)
        self.text_current_music_play_time = '00:00:00'
        self.ids.id_pause_or_proceed_button.source = self.play_icon

    def on_replay(self):
        """重播"""
        if self.sound is None:
            return
        self.seek_value = 0
        self.sound.seek(self.seek_value)
        self.start_play()
        self.on_pause_or_proceed_update_ui()

    def on_red_play(self):
        """红色播放按钮"""
        # 当红色按钮亮起时， 主音轨与互动音轨不可同时播放

    def on_release_sound_volume(self):
        if self.ids.id_sound_volume.source == self.sound_volume_icon:
            self.update_sound_volume(None, 0)
            self.ids.id_sound_volume.source = self.sound_volume_mute_icon
        else:
            self.update_sound_volume(None, self.ids.id_sound_volume_slider.value)
            self.ids.id_sound_volume.source = self.sound_volume_icon

    def update_sound_volume(self, widget, volume):
        _ = widget
        if self.sound and not isinstance(self.sound, SoundSham):
            self.sound.on_volume(None, round(volume / 100, 2))
